package com.util.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

public class SDCardHelper {

	private static boolean isOnLine = false;
	private static long size;
	private static int mbSize = 1024 * 1024;
	private static BufferedOutputStream bus;
	private static ByteArrayOutputStream baos;
	private static BufferedInputStream bis;

	/**
	 * 判断SD卡是否被挂载
	 * @return SD卡是否被挂载
	 */
	public static boolean isSDCardMounted() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return isOnLine = true;
		}
		return isOnLine = false;
	}

	/**
	 * 获取SD卡私有Cache目录的路径
	 * 
	 * @param context
	 * @return SD卡私有Cache目录的路径
	 */
	public static String getSDCardPrivateCacheDir(Context context) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine)
			return context.getExternalCacheDir().getAbsolutePath();
		return "";
	}

	/**
	 * 获取SD卡私有Files目录的路径
	 * 
	 * @param context
	 * @param type
	 * @return SD卡私有Files目录的路径
	 */
	public static String getSDCardPrivateFilesDir(Context context, String type) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine)
			return context.getExternalFilesDir(type).getAbsolutePath();
		return "";
	}

	/**
	 * 获取SD卡公有目录的路径
	 * 
	 * @param type
	 * @return SD卡公有目录的路径
	 */
	public static String getSDCardPublicDir(String type) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine)
			return Environment.getExternalStoragePublicDirectory(type)
					.getAbsolutePath();
		return "";
	}

	/**
	 * 获取SD卡的根路径
	 * 
	 * @return SD卡的根路径
	 */
	public static String getSDCardBaseDir() {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine)
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		return "";
	}

	/**
	 * 获取SD卡的完整空间大小，返回MB
	 * 
	 * @return
	 */
	@SuppressLint("NewApi")
	public static long getSDCardSize() {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			StatFs fs = new StatFs(getSDCardBaseDir());
			long count = fs.getBlockCountLong();
			if (size == 0)
				size = fs.getBlockSizeLong();
			return count * size / mbSize;
		}
		return 0;
	}

	/**
	 * 获取SD卡的可用空间大小，返回MB
	 * 
	 * @return
	 */
	@SuppressLint("NewApi")
	public static long getSDCardAvailableSize() {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			StatFs fs = new StatFs(getSDCardBaseDir());
			long count = fs.getAvailableBlocksLong();
			if (size == 0)
				size = fs.getBlockSizeLong();
			return count * size / mbSize;
		}
		return 0;
	}

	/**
	 * 获取SD卡的剩余空间大小，返回MB
	 * 
	 * @return SD卡的剩余空间大小，返回MB
	 */
	@SuppressLint("NewApi")
	public static long getSDCardFreeSize() {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			StatFs fs = new StatFs(getSDCardBaseDir());
			long count = fs.getFreeBlocksLong();
			if (size == 0)
				size = fs.getBlockSizeLong();
			return count * size / mbSize;
		}
		return 0;
	}

	/**
	 * 关闭输出流
	 */
	private static void doClose() {
		if (bus != null)
			try {
				bus.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (baos != null)
			try {
				baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (bis != null)
			try {
				bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	/**
	 * 往SD卡的自定义目录下保存文件
	 * 
	 * @param data
	 *            数据内容
	 * @param dir
	 *            sd卡中的目录
	 * @param fileName
	 *            文件名
	 * @return boolean
	 */
	public static boolean saveFileToSDCardCustomDir(byte[] data, String dir,
			String fileName) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			File file = new File(getSDCardBaseDir() + File.separator + dir);
			if (!file.exists()) {
				file.mkdirs();
			}
			try {
				bus = new BufferedOutputStream(new FileOutputStream(new File(
						file, fileName)));
				bus.write(data);
				bus.flush();
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}
		}
		return false;
	}

	/**
	 * 往SD卡的私有Cache目录下保存文件
	 * 
	 * @param data
	 *            数据
	 * @param fileName
	 *            文件名
	 * @param context
	 *            上下文对象
	 * @return
	 */
	public static boolean saveFileToSDCardPrivateCacheDir(byte[] data,
			String fileName, Context context) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			File file = context.getExternalCacheDir();
			try {
				bus = new BufferedOutputStream(new FileOutputStream(new File(
						file, fileName)));
				bus.write(data);
				bus.flush();
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}
		}
		return false;
	}

	/**
	 * 往SD卡的私有Files目录下保存文件
	 * 
	 * @param data
	 *            数据
	 * @param type
	 * @param fileName
	 *            文件名
	 * @param context
	 *            上下文对象
	 * @return
	 */
	public static boolean saveFileToSDCardPrivateFilesDir(byte[] data,
			String type, String fileName, Context context) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			File file = context.getExternalFilesDir(type);
			try {
				bus = new BufferedOutputStream(new FileOutputStream(new File(
						file, fileName)));
				bus.write(data);
				bus.flush();
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}
		}
		return false;
	}

	/**
	 * 往SD卡的公有目录下保存文件
	 * 
	 * @param data
	 *            数据
	 * @param type
	 * @param fileName
	 *            文件名
	 * @return
	 */
	public static boolean saveFileToSDCardPublicDir(byte[] data, String type,
			String fileName) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine) {
			File file = Environment.getExternalStoragePublicDirectory(type);
			try {
				bus = new BufferedOutputStream(new FileOutputStream(new File(
						file, fileName)));
				bus.write(data);
				bus.flush();
				return true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}

		}
		return false;
	}

	/**
	 * 获取文件
	 * @param filePath
	 *            文件路径
	 * @return
	 */
	public static byte[] loadFileFromSDCard(String filePath) {
		if (!isOnLine) {
			isSDCardMounted();
		}
		if (isOnLine||(filePath.indexOf("sdcard"))==-1) {
			baos = new ByteArrayOutputStream();
			byte b[] = new byte[1024 * 4];
			int len;
			try {
				bis = new BufferedInputStream(new FileInputStream(filePath));
				while ((len = bis.read(b)) != -1) {
					baos.write(b, 0, len);
					baos.flush();
				}
				return baos.toByteArray();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}
		}
		return null;
	}
}
